<template>
  <div>
    <div class="box">
      <el-form ref="resetForm" :model="resetForm" :rules="rules" label-width="120px">
        <el-form-item label="原密码" prop="oldPass">
          <el-input v-model="resetForm.oldPass" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPass1">
          <el-input v-model="resetForm.newPass1" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="newPass2">
          <el-input v-model="resetForm.newPass2" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('resetForm')">保存</el-button>
          <el-button @click="handleResetForm('resetForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import {resetPassword} from '@/api/admin.js'
  export default {
    name: 'ResetPass',
    data() {
      var checkPass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.resetForm.newPass1) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        user: null,
        resetForm: {
          oldPass: '',
          newPass1: '',
          newPass2: '',
        },
        rules: {
          oldPass: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
          newPass1: [{required: true, message: '请输入新密码', trigger: 'blur' }],
          newPass2: [{ validator: checkPass, trigger: 'blur' }],
        }
      }
    },
    mounted() {
      let u = window.sessionStorage.getItem('user')
      if(u != null) {
        this.user = JSON.parse(u)
        console.log('mount', this.user);
      }
    },
    methods: {
      // 修改密码
      submitForm(formName) {
        if(this.user == null) {
          this.$message.error("当前用户已失效，请重新登录")
          return
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let param = {
              userId: this.user.userId,
              oldPass: this.resetForm.oldPass,
              newPass: this.resetForm.newPass1
            }
            resetPassword(param).then(res => {
              if(res.code == 200) {
                this.$message.success("密码修改成功")
              }
              else {
                let msg = res.msg
                this.$message.error(msg)
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 重置组件
      handleResetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style scoped>
  .box {
    margin: 10px;
  }
</style>
